#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "cube.h"
#include "map.h"

#include <QPainter>
#include <QTimer>
#include <QKeyEvent>
#include <QPolygon>
<<<<<<< .mine
#include <QFileDialog>
#include <QMessageBox>
=======
#include <QDebug>
>>>>>>> .r36

#include <iostream>
#include "math.h"
using namespace std;

MainWindow::MainWindow(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWindow)

{

    ui->setupUi(this);
}

MainWindow::MainWindow(QWidget *parent, QString newFilepath, QString gameFile) :
    QWidget(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setGeometry(this->x(),this->y(), 640, 640);
    this->setFocus();

    //Create the game map
    gameMap = new Map(this, 25, 25, filepath);
    //Add cubes to the game map
    gameMap->loadCubes();

    //Set File Path
    this->filepath = newFilepath;

    //Create Background Image
    QString space_background = this->filepath + "Images/bg.png";
    qDebug() << "mainWindow space_background: " << space_background << endl;
    bg = QImage(space_background);

    //Connect the timer to the paint method
    //and start the timer.
<<<<<<< .mine
    gameTimer = new QTimer(this);
=======
    counter = 0;
    this->gameTimer = new QTimer(this);
>>>>>>> .r36
    connect(gameTimer, SIGNAL(timeout()), this, SLOT(repaint()));
    connect(this, SIGNAL(shipCrashed()), gameTimer, SLOT(stop()));
    connect(this, SIGNAL(timerStart()), gameTimer, SLOT(start()));
    gameTimer->start(33);
<<<<<<< .mine
    paused = false;
=======

>>>>>>> .r36
}

MainWindow::~MainWindow()
{
    delete ui;
}

//Update method that gets run at 30 f/s
void MainWindow::paintEvent(QPaintEvent *event)
{
<<<<<<< .mine
    gameMap->counter++;
    cout<<gameMap->counter<<endl;
=======
    gameMap->counter++;

    //Increment by x every y seconds
    int x = 1;
    int y = 2;
    if(this->gameMap->counter % (y*30) == 0)
        gameMap->speed += x;


//Update label displaying speed
    ui->speedlbl->setText("Speed: " + QString::number(gameMap->speed));

>>>>>>> .r36
    //Create the painter
    QPainter painter(this);
    QPen pen( Qt::white );
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(pen);

    //Draw a window-sized background image
    painter.setBrush(QBrush(Qt::white, Qt::SolidPattern));
    QRect imageRect(0,0,this->width(), this->height());
    painter.drawImage(imageRect, bg);
    //painter.drawImage(0,0,bg);

    //Move the camera/ship if the user is pressing arrow keys
    gameMap->camUpdate();

    //Draw the tunnel
    painter.setBrush(QBrush(Qt::white, Qt::SolidPattern));
    double leftX = ((0 - gameMap->x) * (this->width() / 30.0)) / (.001) + (this->width() / 2.0);
    double rightX = ((50 - gameMap->x) * (this->width() / 30.0))/ (.001) + (this->width() / 2.0);
    double topY = ((0 - gameMap->y) * (this->height() / 30.0)) / (.001)+ (this->height() / 2.0);
    double bottomY = ((50 - gameMap->y) * (this->height() / 30.0))/ (.001) + (this->height() / 2.0);
    double centerX = this->width() / 2.0;
    double centerY = this->height() / 2.0;

    painter.drawLine(centerX, centerY, leftX, topY);
    painter.drawLine(centerX, centerY, leftX, bottomY);
    painter.drawLine(centerX, centerY, rightX, topY);
    painter.drawLine(centerX, centerY, rightX, bottomY);

    pen.setColor(Qt::black);

    //Get each cube in the gameMap...
    QList<Cube *> allCubes = gameMap->findChildren <Cube *>();

    //Sort them by their distance from the camera
    QMap<double, Cube *> map;
    foreach (Cube * c1, allCubes)
        map.insert(c1->camDistance, c1);
    allCubes = map.values();

    for (int i = allCubes.size() - 1; i >= 0; --i)
    {

        //Z-update (Move the cube forward)
        allCubes[i]->zUpdate();

        //camDistance update (Distance of the cube from the camera
        double temp = sqrt(((double)allCubes[i]->x - gameMap->x) *
                           (allCubes[i]->x - gameMap->x) +
                           (allCubes[i]->y - gameMap->y) *
                           (allCubes[i]->y - gameMap->y));
        allCubes[i]->camDistance = sqrt(temp*temp + ((double)allCubes[i]->z * allCubes[i]->z));
        allCubes[i]->camDistance *= 10;

        //Visibility update (Check if the cube should be displayed)
        allCubes[i]->visUpdate();

        //Check for collision        
        if(allCubes[i]->crashTest())
            emit shipCrashed();

        //Delete it?
        if(allCubes[i]->z < 0)
            allCubes[i]->deleteLater();
        else
        {
            //If the cube is visible...
            if(allCubes[i]->visible == true)
            {
                //Select the corrent color
                if(allCubes[i]->color == 0)
                    painter.setBrush(QBrush(Qt::gray, Qt::SolidPattern));
                if(allCubes[i]->color == 1)
                    painter.setBrush(QBrush(Qt::red, Qt::SolidPattern));
                if(allCubes[i]->color == 2)
                    painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));

                //Distance fade
                if(allCubes[i]->z > 400)
                    painter.setOpacity(-(allCubes[i]->z /  400.0) + 2);
                else
                    painter.setOpacity(1);

                //Draw the three polygons
                QPolygon p1;

                //Select the order to draw the sides
                int *orderTest = allCubes[i]->makePolygon(2);
                if((orderTest[6] > orderTest[0]) && (orderTest[4] < orderTest[2]))
                {
                    //Draw the side
                    p1.setPoints(4, allCubes[i]->makePolygon(1));
                    painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));
                    painter.drawPolygon(p1);
                    //Draw the bottom/top
                    p1.setPoints(4, allCubes[i]->makePolygon(2));
                    painter.setBrush(QBrush(Qt::blue, Qt::SolidPattern));
                    painter.drawPolygon(p1);
                }
                else
                {
                    //Draw the bottom/top
                    p1.setPoints(4, allCubes[i]->makePolygon(2));
                    painter.setBrush(QBrush(Qt::blue, Qt::SolidPattern));
                    painter.drawPolygon(p1);
                    //Draw the side
                    p1.setPoints(4, allCubes[i]->makePolygon(1));
                    painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));
                    painter.drawPolygon(p1);
                }

                //Draw the front
                p1.setPoints(4, allCubes[i]->makePolygon(0));
                painter.setBrush(QBrush(Qt::red, Qt::SolidPattern));
                painter.drawPolygon(p1);
            }
        }

    }
    //Display collision cube

//    Cube collisionDisplay(gameMap, gameMap->x, gameMap->y + gameMap->shipOffset, 0, gameMap->shipWidth, 0);
//    QPolygon p2;
//    p2.setPoints(4, collisionDisplay.makePolygon(0));
//    painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));
//    painter.drawPolygon(p2);

    //Draw the ship
    QString shipDraw = shipFile();
    painter.setOpacity(1);
    QImage spaceShip(shipDraw);
    double imageWidth = 250;
    painter.drawImage(((this->width() / 2) - (imageWidth / 2)),
                      ((this->height() / 2) + 100 - (imageWidth / 2)),
                      spaceShip);


    painter.end();
}

//Handles key presses
void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if(event->type() == QEvent::KeyPress)
    {
        //Arrow keys - move the ship
        if(event->key() == Qt::Key_Left)
            gameMap->left = true;
        if(event->key() == Qt::Key_Right)
            gameMap->right = true;
        if(event->key() == Qt::Key_Up)
            gameMap->down = true;
        if(event->key() == Qt::Key_Down)
            gameMap->up = true;

//        //Accelerate and decelerate
//        if(event->key() == Qt::Key_Z)
//            gameMap->decelerate = true;
//        if(event->key() == Qt::Key_X)
//            gameMap->accelerate = true;

        //Cheat mode
        if(event->key() == Qt::Key_R)
            emit timerStart();
<<<<<<< .mine
        if (event->key() == Qt::Key_P){
            if(!paused){
            gameTimer->stop();
            paused = true;
            }else if(paused){
                gameTimer->start(33);
                paused = false;
            }
        }
        if(event->key() == Qt::Key_S)
            gameMap->saveMap();
=======

        //Pausing the game
        if(event->key() == Qt::Key_P)
        {
            if(this->gameTimer->isActive())
                this->gameTimer->stop();
            else
                this->gameTimer->start();
        }

        //Save the game
        if(event->key() == Qt::Key_S)
        {
            this->gameTimer->stop();
            this->gameMap->saveMap();
        }
        //Load the game
        if(event->key() == Qt::Key_L)
        {
            this->gameTimer->stop();
            this->gameMap->loadMap();
            this->paintEvent(NULL);
        }
>>>>>>> .r36
    }
}

//Handles key releases
void MainWindow::keyReleaseEvent(QKeyEvent *event)
{
    if(event->type() == QEvent::KeyRelease)
    {
        //Arrow keys - move the ship
        if(event->key() == Qt::Key_Left)
            gameMap->left = false;
        if(event->key() == Qt::Key_Right)
            gameMap->right = false;
        if(event->key() == Qt::Key_Up)
            gameMap->down = false;
        if(event->key() == Qt::Key_Down)
            gameMap->up = false;

        //Accelerate and decelerate
//        if(event->key() == Qt::Key_Z)
//            gameMap->decelerate = false;
//        if(event->key() == Qt::Key_X)
//            gameMap->accelerate = false;        
    }
}

QString MainWindow::shipFile()
{
    QString ship01 = filepath + "Images/0001.png";
    QString ship02 = filepath + "Images/0002.png";
    QString ship03 = filepath + "Images/0003.png";
    QString ship04 = filepath + "Images/0004.png";
    QString ship05 = filepath + "Images/0005.png";
    QString ship06 = filepath + "Images/0006.png";
    QString ship07 = filepath + "Images/0007.png";
    QString ship08 = filepath + "Images/0008.png";
    QString ship09 = filepath + "Images/0009.png";
    QString shipDraw;

    if(gameMap->up == true)
    {
        if(gameMap->left == true)
            shipDraw = ship01;
        else if(gameMap->right == true)
            shipDraw = ship03;
        else
            shipDraw = ship02;
    }
    else if(gameMap->down == true)
    {
        if(gameMap->left == true)
            shipDraw = ship07;
        else if(gameMap->right == true)
            shipDraw = ship09;
        else
            shipDraw = ship08;
    }
    else
    {
        if(gameMap->left == true)
            shipDraw = ship04;
        else if(gameMap->right == true)
            shipDraw = ship06;
        else
            shipDraw = ship05;
    }

    return shipDraw;
}

